<template>
  <view class="pickup-other">
    <scroll-view scroll-y class="content">
      <view class="section">
        <view class="section-title">📝 服务内容</view>
        <view class="form-item">
          <textarea
            v-model="formData.pickupRemark"
            placeholder="请描述你需要的服务内容"
            placeholder-class="placeholder"
            maxlength="500"
          />
        </view>
      </view>

      <view class="section">
        <view class="section-title">📫 收货地址（仅用于获取手机号）</view>
        <view class="form-item address-card" @click="selectAddress">
          <view v-if="selectedAddress" class="address-line">
            <text class="name">{{ selectedAddress.contactName }}</text>
            <text class="phone">{{ selectedAddress.contactPhone }}</text>
          </view>
          <view v-else class="placeholder">请选择联系方式</view>
        </view>
        <view class="tip-small">地址将保护，仅用于获取手机号，便于接单后联系，不用于配送</view>
      </view>

      <view class="section">
        <view class="section-title">📍 服务地址（选填）</view>
        <view class="form-item">
          <input
            v-model="formData.pickupAddress"
            placeholder="可填写服务发生地点，如教学楼A-101"
            placeholder-class="placeholder"
          />
        </view>
      </view>

      <view class="section">
        <view class="section-title">💰 服务费用</view>
        <view class="fee-input">
          <text>建议: ¥{{ categoryInfo.basePrice || defaultBasePrice }}</text>
          <view class="input-wrapper">
            <text>¥</text>
            <input
              v-model.number="formData.serviceFee"
              type="digit"
              placeholder="请输入金额"
            />
          </view>
        </view>
        <view class="fee-tip">
          <text class="tip-icon">💡</text>
          <text class="tip-text">费用越高，接单越快哦~</text>
        </view>
      </view>

      <view class="section">
        <view class="section-title">🗒️ 备注（选填）</view>
        <view class="form-item">
          <textarea
            v-model="formData.deliveryRemark"
            placeholder="补充说明，例如时间要求、注意事项等"
            placeholder-class="placeholder"
            maxlength="200"
          />
        </view>
      </view>

      <view class="section">
        <view class="section-title">🖼️ 相关图片（选填）</view>
        <MultiImageUploader
          :images="serviceImages"
          title="上传图片"
          tip="可上传与服务需求相关的截图或照片"
          :max-count="9"
          module="order/other"
          @update:images="updateServiceImages"
          @upload-success="handleImageUploadSuccess"
          @upload-error="handleImageUploadError"
        />
      </view>
    </scroll-view>

    <view class="footer">
      <button class="submit-btn" @click="handleSubmit">
        立即发布 ¥{{ formData.serviceFee || 0 }}
      </button>
    </view>
  </view>
</template>

<script>
import { createPickupOrder, getCategoryList } from '@/api/pickup'
import MultiImageUploader from '@/components/MultiImageUploader.vue'
import { getAddressList } from '@/api/address'

export default {
  components: { MultiImageUploader },
  data() {
    return {
      categoryId: '',
      categoryInfo: {},
      defaultBasePrice: 3,
      platformFeeRate: 0.25,
      selectedAddress: null,
      formData: {
        categoryId: '',
        pickupAddress: '',
        pickupRemark: '',
        deliveryAddress: '',
        receiverName: '',
        receiverPhone: '',
        deliveryRemark: '',
        serviceFee: 0,
        firstImage: '',
        secondImage: ''
      },
      serviceImages: []
    }
  },
  computed: {
    platformFee() {
      return (this.formData.serviceFee * this.platformFeeRate).toFixed(2)
    },
    riderEarning() {
      return (this.formData.serviceFee - this.platformFee).toFixed(2)
    }
  },
  onLoad(options) {
    if (options && options.categoryId) {
      this.categoryId = options.categoryId
      this.formData.categoryId = options.categoryId
    }
    this.loadPlatformFeeRate()
    this.loadCategoryInfo()
    this.loadDefaultAddress()
  },
  onShow() {
    if (this.selectedAddress) {
      this.updateDeliveryInfo()
    }
  },
  methods: {
    async loadPlatformFeeRate() {
      try {
        const { getConfig } = require('@/api/config')
        const val = await getConfig('pickup_platform_fee_rate')
        const percent = parseFloat(val)
        if (!isNaN(percent) && percent >= 0 && percent <= 100) {
          this.platformFeeRate = +(percent / 100).toFixed(4)
        } else {
          this.platformFeeRate = 0.25
        }
      } catch (_) {
        this.platformFeeRate = 0.25
      }
    },
    async loadCategoryInfo() {
      try {
        const list = await getCategoryList()
        if (!this.categoryId) {
          const other = list.find(i => (i.name || '').includes('其他'))
          if (other) {
            this.categoryId = other.id
            this.formData.categoryId = other.id
            this.categoryInfo = other
          }
        } else {
          this.categoryInfo = list.find(i => String(i.id) === String(this.categoryId)) || {}
        }
        const base = this.categoryInfo.basePrice || this.defaultBasePrice
        if (!this.formData.serviceFee) this.formData.serviceFee = base
        uni.setNavigationBarTitle({ title: `发布【${this.categoryInfo.name || '其他服务'}】` })
      } catch (e) {
        const base = this.defaultBasePrice
        if (!this.formData.serviceFee) this.formData.serviceFee = base
        uni.setNavigationBarTitle({ title: '发布【其他服务】' })
      }
    },
    async loadDefaultAddress() {
      try {
        const list = await getAddressList()
        const def = list.find(item => item.isDefault === 1)
        if (def) {
          this.selectedAddress = def
          this.updateDeliveryInfo()
        } else if (list && list.length > 0) {
          this.selectedAddress = list[0]
          this.updateDeliveryInfo()
        }
      } catch (e) {
        // 忽略加载失败
      }
    },
    selectAddress() {
      uni.navigateTo({ url: '/pages/address/list?select=true' })
    },
    formatAddress(item) {
      let address = ''
      if (item.building) address += item.building
      if (item.room) address += (address ? '-' : '') + item.room
      if (item.detail) address += (address ? ' ' : '') + item.detail
      return address || '暂无详细地址'
    },
    updateDeliveryInfo() {
      if (this.selectedAddress) {
        this.formData.deliveryAddress = this.formatAddress(this.selectedAddress)
        this.formData.receiverName = this.selectedAddress.contactName
        this.formData.receiverPhone = this.selectedAddress.contactPhone
      }
    },
    updateServiceImages(images) {
      this.serviceImages = images
    },
    handleImageUploadSuccess() {},
    handleImageUploadError() {},
    validateForm() {
      if (!this.formData.pickupRemark) {
        uni.showToast({ title: '请填写服务内容', icon: 'none' })
        return false
      }
      if (!this.formData.receiverPhone) {
        uni.showToast({ title: '请选择收货地址以获取手机号', icon: 'none' })
        return false
      }
      const base = this.categoryInfo.basePrice || this.defaultBasePrice
      if (!this.formData.serviceFee || this.formData.serviceFee < base) {
        uni.showToast({ title: `服务费不能低于¥${base}`, icon: 'none' })
        return false
      }
      if (!this.formData.categoryId) {
        uni.showToast({ title: '未配置“其他服务”分类，请联系后台配置', icon: 'none' })
        return false
      }
      return true
    },
    async handleSubmit() {
      if (!this.validateForm()) return
      try {
        uni.showLoading({ title: '创建订单中...' })
        const submitData = { ...this.formData }
        // 如果未填写服务地址，默认为"其他服务"
        if (!submitData.pickupAddress) {
          submitData.pickupAddress = '其他服务'
        }
        // 将收货地址也改为"其他服务"，避免订单详情显示真实地址
        submitData.deliveryAddress = '其他服务'
        submitData.firstImage = JSON.stringify(this.serviceImages)
        submitData.secondImage = JSON.stringify([])
        const res = await createPickupOrder(submitData)
        uni.hideLoading()
        uni.showToast({ title: '订单创建成功', icon: 'success' })
        setTimeout(() => {
          uni.navigateTo({ url: '/pages/pickup/my-publish' })
        }, 1500)
      } catch (error) {
        uni.hideLoading()
        uni.showToast({ title: (error && (error.msg || error.message)) || '创建订单失败', icon: 'none' })
      }
    }
  }
}
</script>

<style scoped>
.pickup-other {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #F5F5F5;
}
.content {
  flex: 1;
  padding: 24rpx;
}
.section {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
}
.section-title {
  font-size: 30rpx;
  font-weight: bold;
  margin-bottom: 24rpx;
}
.form-item {
  margin-bottom: 24rpx;
}
.form-item:last-child { margin-bottom: 0; }
.form-item input,
.form-item textarea {
  width: 100%;
  padding: 24rpx;
  background: #F8F9FA;
  border-radius: 8rpx;
  font-size: 28rpx;
}
.form-item textarea { height: 140rpx; }
.placeholder { color: #999; }
.address-card {
  background: #F8F9FA;
  border-radius: 8rpx;
  padding: 24rpx;
  cursor: pointer;
  transition: all 0.3s ease;
}
.address-card:active {
  background: #E8EAED;
}
.address-line {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}
.address-line .name {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
}
.address-line .phone {
  font-size: 26rpx;
  color: #666;
}
.tip-small {
  font-size: 24rpx;
  color: #999;
  margin-top: 12rpx;
}
.fee-input {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}
.input-wrapper {
  display: flex;
  align-items: center;
  background: #F8F9FA;
  border-radius: 8rpx;
  padding: 24rpx;
}
.input-wrapper text {
  margin-right: 8rpx;
  color: #FF6B6B;
  font-weight: bold;
}
.input-wrapper input { flex: 1; width: 200rpx; }
.fee-tip {
  background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
  border-radius: 12rpx;
  padding: 24rpx;
  display: flex;
  align-items: center;
  gap: 16rpx;
}
.fee-tip .tip-icon { font-size: 36rpx; }
.fee-tip .tip-text { flex: 1; font-size: 26rpx; color: #f57c00; line-height: 1.5; }
.footer {
  padding: 24rpx;
  background: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}
.submit-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #4ECDC4, #44A08D);
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  border-radius: 44rpx;
  border: none;
}
</style>
